package com.lehecai.core.search.entity;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;

/**
 * User: sunshow
 * Date: 13-4-10
 * Time: 下午4:05
 */
public abstract class AbstractSearchEntity<T> implements ISearchEntity {

    private static final long serialVersionUID = 5385275219149330536L;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getPrimaryKeyMeta() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.getEntityKey()).append(", id=").append(this.getId());
        return sb.toString();
    }

    /**
     * 获取泛型的类对象
     * @return TSearch
     */
    @SuppressWarnings("unchecked")
    protected Class<T> getActualType() {
        ParameterizedType paramType = (ParameterizedType)this.getClass().getGenericSuperclass();

        Class<T> clazz = (Class<T>)paramType.getActualTypeArguments()[0];

        return clazz;
    }

    protected T createSourceInstance() {
        try {
            return this.getActualType().newInstance();
        } catch (Exception e) {
            logger.error("实例化出错", e);
            return null;
        }
    }

    public T convert() throws Exception {
        T sourceEntity = this.createSourceInstance();

        SearchEntityPropertyDefine[] definition = SearchEntityDefine.get(this.getEntityKey());

        for (SearchEntityPropertyDefine propertyDefine : definition) {
            Object property = PropertyUtils.getProperty(this, propertyDefine.getPropertyName());
            if (property != null) {
                BeanUtils.setProperty(sourceEntity, propertyDefine.getSourcePropertyName(), property);
            }
        }

        return sourceEntity;
    }
}
